package com.polaris.live.manager

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.StringUtils
import com.polaris.live.App
import com.polaris.live.R
import com.polaris.live.common.manager.CoroutineScopeManager
import com.polaris.live.im.sfs.bean.live.CallSignalingMessage
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * 应用通知管理
 *
 * @author Created by 天晴 on 2024/7/15 11:25
 * @since 1.0.0
 **/
object MNotificationManager {

    /**
     * 通话消息推送通道ID
     */
    private val CALL_CHANNEL_ID = "${AppUtils.getAppPackageName()}_call_channel_001"

    /**
     * 初始化
     */
    fun init() {
        createNotificationCallChannel()
    }

    /**
     * 创建一个推送通道
     * Android 8.0 以上需要创建
     * channelName
     * channelDescription
     * importance 通道等级
     */
    private fun createNotificationChannel(
        channelName: String,
        channelDescription: String,
        channelId: String,
        importance: Int,
    ) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(channelId, channelName, importance)
            channel.description = channelDescription
            val notificationManager: NotificationManager =
                App.instance.getSystemService(NotificationManager::class.java)
            notificationManager.createNotificationChannel(channel)
        }
    }

    /**
     * 创建一个通话推送通道
     */
    private fun createNotificationCallChannel() {
        createNotificationChannel(
            "CALL_CHANNEL",
            "Used to display phone messages",
            CALL_CHANNEL_ID,
            NotificationManager.IMPORTANCE_HIGH
        )
    }

    private var timeJob: Job? = null

    /**
     * 通知Id 随便取的
     */
    private var mCallNotificationId = 1024
    private val largeIcon = BitmapFactory.decodeResource(App.instance.resources, R.mipmap.ic_launcher)
    fun sendCallNotification(sing: CallSignalingMessage) {
        val notificationManager = NotificationManagerCompat.from(App.instance)
        notificationManager.cancel(mCallNotificationId) //移除相同通知
        val intent = App.instance.packageManager.getLaunchIntentForPackage(AppUtils.getAppPackageName())?.apply {
            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP
        }
        val pendingIntent = PendingIntent.getActivity(App.instance, 0, intent, PendingIntent.FLAG_IMMUTABLE)
        val builder = NotificationCompat.Builder(App.instance, CALL_CHANNEL_ID)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setLargeIcon(largeIcon)
            .setContentTitle(StringUtils.getString(com.polaris.live.translation.R.string.call_string))
            .setContentText("${sing.nickname}")
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setContentIntent(pendingIntent)
            .setOngoing(true)
            .setAutoCancel(true)
        notificationManager.notify(mCallNotificationId, builder.build())
        startTime()
    }

    private fun startTime() {
        cancelTime()
        timeJob = CoroutineScopeManager.mainScope.launch {
            try {
                delay(15000)
                cancelCallNotification()
            } finally {
                if (timeJob == coroutineContext[Job]) {
                    timeJob?.cancel()
                    timeJob = null
                }
            }
        }
    }

    private fun cancelTime() {
        timeJob?.cancel()
        timeJob = null
    }

    /**
     * 回到前台
     */
    fun backForeground() {
        cancelTime()
        cancelCallNotification()
    }

    /**
     * 取消电话通知
     */
    fun cancelCallNotification() {
        val notificationManager = NotificationManagerCompat.from(App.instance)
        notificationManager.cancel(mCallNotificationId)
    }

}